<?php

use Illuminate\Http\Request;

// 计算身份证校验码，根据国家标准GB 11643-1999
function checkCertNo($idcard)
{
    $len = strlen($idcard);
    if ($len != 18) {
        return false;
    }
    $idcard_base = substr($idcard, 0, 17);
    //加权因子
    $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    //校验码对应值
    $verify_number_list = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    $checksum = 0;
    for ($i = 0; $i < strlen($idcard_base); $i++) {
        $checksum += substr($idcard_base, $i, 1) * $factor[$i];
    }
    $mod = $checksum % 11;

    return strtoupper(substr($idcard, 17, 1)) == $verify_number_list[$mod];
}


//生成订单号
function createOrderSn()
{
    return 'QHADM' . strtoupper(date('Ymd', time())) . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
}


//解析框架异常错误-获取第一条
function getValidateMessage($message)
{
    $messageArr = json_decode(json_encode($message), true);
    $msg = '';
    foreach ($messageArr as $val) {
        $msg = $val[0];
    }

    return $msg;
}


//出生日期转年龄
function birthToAge($birth, $type = false)
{
    if ($birth == '0000-00-00') {
        return 0;
    }
    if ($type) {
        $birth = strtotime($birth);
    }

    //格式化出生时间年月日
    $byear = date('Y', $birth);
    $bmonth = date('m', $birth);
    $bday = date('d', $birth);

    //格式化当前时间年月日
    $tyear = date('Y');
    $tmonth = date('m');
    $tday = date('d');

    //开始计算年龄
    $age = $tyear - $byear;
    if ($bmonth > $tmonth || $bmonth == $tmonth && $bday > $tday) {
        $age--;
    }

    return $age;
}

function pwdHash($str_password = '', $real_password = '', $type = false)
{
    if (!$str_password && !$real_password) {
        return false;
    }
    require_once(base_path() . '/app/Plugins/Phpass/PasswordHash.php');
    $hasher = new PasswordHash(8, false);
    if (!$type) {
        return $hasher->HashPassword($str_password);
    } else {
        return $hasher->CheckPassword($str_password, $real_password);
    }
}

//截取字符串
function substr_format($text, $length, $replace = '..', $encoding = 'UTF-8')
{
    if ($text && mb_strlen($text, $encoding) > $length) {
        return mb_substr($text, 0, $length, $encoding) . $replace;
    }

    return $text;
}

function todayLeftTime()
{
    return (\Carbon\Carbon::tomorrow() - time());
}

function checkGoodNumber($number)
{
    $is_good_number = app('redis')->hexists('goodNumber', $number);

    return $is_good_number ? 1 : 0;
}

function getStrTime($hour)
{
    $no = $hour;
    if ($no > 0 && $no <= 6) {
        return "凌晨";
    }
    if ($no > 6 && $no < 12) {
        return "上午";
    }
    if ($no >= 12 && $no <= 18) {
        return "下午";
    }
    if ($no > 18 && $no <= 24) {
        return "晚上";
    }
}

function functionLimit()
{
    $request = (new Request())->capture();
    $clienttype = $request->header('clientType');
    $channelid = $request->header('channelid');
    if ($clienttype == 'android' && $channelid == 'kuaishou') {
        return true;
    }
    $app_version = str_replace('.', '', $request->header('appVersion'));
    $config = app('model_config')->getValue('IOS_VERSION');
    $config = json_decode($config, true);
    $config_version = $config['otherVersion'] ?? '';
    if ($config_version) {
        $config_version = str_replace('.', '', $config_version);
    }
    if ($clienttype == 'appstore' && $app_version > $config_version) {
        return true;
    }

    return false;
}

//判断是否是进入房间隐身用户
function isRoomInvisibleUser($user_id, $room_id = 0)
{
    //判断是否是隐身进入房间用户
    $invisible = false;
    $invisible_users = app('model_config')->getValue('JOIN_ROOM_INVISIBLE_USER');
    $user_code = app('model_user_data')->getUserCode($user_id);
    if (is_array($invisible_users) && in_array($user_code, $invisible_users)) {
        if (app('model_user_config')->getUserConfigValue($user_id, 'is_invisible') == 1) {
            $invisible = true;
        }
    }

    return $invisible;
}

//修饰时间
function format_time($time, $mode = false)
{
    if (!empty($time)) {
        $t = time() - $time;
        $f = [
            '31536000' => '年',
            '2592000'  => '个月',
            '604800'   => '星期',
            '86400'    => '天',
            '3600'     => '小时',
            '60'       => '分钟',
            '1'        => '秒',
        ];
        foreach ($f as $k => $v) {
            if (0 != $c = floor($t / (int)$k)) {
                return $c . $v . '前';
            }
        }
    }

    if ($mode) {
        return '1秒前';
    }

    return date('Y-m-d H:i:s', time());
}


//获得客户端基本信息
function getClientInfo()
{
    $request = (new Request())->capture();
    $clientType = $request->header('clientType', '');
    $channelId = $request->header('channelid', '');
    $appVersion = $request->header('appVersion', '');

    $data = [
        'clientType' => $clientType,
        'channelId'  => $channelId,
        'appVersion' => $appVersion,
    ];

    return $data;
}

function arraySort($array, $keys, $sort = 'asc')
{
    $newArr = $valArr = [];
    foreach ($array as $key => $value) {
        $valArr[$key] = $value[$keys];
    }
    ($sort == 'asc') ? asort($valArr) : arsort($valArr);
    reset($valArr);
    foreach ($valArr as $key => $value) {
        $newArr[$key] = $array[$key];
    }

    return $newArr;
}

//数字格式话
function numberFormat($number)
{
    $num = round($number / 10000, 2);
    if ($num > 1) {
        $number = $num . 'w';
    }

    return $number;
}

function get_rand($array = [])
{
    $rs = '';                    //中奖结果
    $proSum = array_sum($array); //概率数组的总概率精度
    //概率数组循环
    foreach ($array as $key => $proCur) {
        $randNum = mt_rand(1, $proSum);
        if ($randNum <= $proCur) {
            $rs = $key;
            break;
        } else {
            $proSum -= $proCur;
        }
    }
    unset($array);

    return $rs;
}

function lockApi($lock_key, $expire_time = 1000, $lock_value = 1)
{
    if (!app('redis')->setnx($lock_key, $lock_value)) {
        return false;
    }
    app('redis')->pexpire($lock_key, $expire_time);

    return true;
}

function unlockApi($lock_key)
{
    app('redis')->del($lock_key);
}


//获得系统配置
function get_sys_config($key = '')
{
    $config = app('redis')->get('DB_CONFIG_DATA');

    $config_arr = json_decode($config, true);

    if (!empty($key)) {
        return isset($config_arr[$key]) ? $config_arr[$key] : '';
    }

    return $config_arr;
}

//获取当前毫秒
function get_microtime()
{
    [$msec, $sec] = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);

    return $msectime;
}


function captcha()
{
    $image = imagecreatetruecolor(100, 30);
    $bgcolor = imagecolorallocate($image, 255, 255, 255);
    imagefill($image, 0, 0, $bgcolor);
    $content = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    $captcha = "";
    for ($i = 0; $i < 4; $i++) {
        $fontsize = 10;
        $fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
        $fontcontent = substr($content, mt_rand(0, strlen($content)), 1);
        $captcha .= $fontcontent;
        $x = ($i * 100 / 4) + mt_rand(5, 10);
        $y = mt_rand(5, 10);
        imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
    }
    for ($i = 0; $i < 200; $i++) {
        $pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
        imagesetpixel($image, mt_rand(1, 99), mt_rand(1, 29), $pointcolor);
    }
    for ($i = 0; $i < 3; $i++) {
        $linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
        imageline($image, mt_rand(1, 99), mt_rand(1, 29), mt_rand(1, 99), mt_rand(1, 29), $linecolor);
    }

    return [
        'code' => $captcha,
        'img'  => $image,
    ];
//    header('content-type:image/png');
//    imagepng($image);
//    imagedestroy($image);
}


//获取图形地址
function setImgUrl()
{
    $dir = apppath() . date('Ymd_H', time()) . rand(1000, 9999);
    if (!file_exists($dir)) {
        mkdir($dir);
    }
}

/**
 * +----------------------------------------------------------
 * 生成随机字符串
 * +----------------------------------------------------------
 *
 * @param  int  $length  要生成的随机字符串长度
 * @param  string  $type  随机码类型：0，数字+大小写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
 * +----------------------------------------------------------
 * @return string
 * +----------------------------------------------------------
 */
function randCode($length = 5, $type = 0)
{
    $arr = [1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|"];
    if ($type == 0) {
        array_pop($arr);
        $string = implode("", $arr);
    } elseif ($type == "-1") {
        $string = implode("", $arr);
    } else {
        $string = $arr[$type];
    }
    $count = strlen($string) - 1;
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $string[rand(0, $count)];
    }

    return $code;
}

/**
 * @Desc:脱敏处理,很多地方使用到了,请勿删除
 * @param $str
 * @param $start
 * @param $len
 * @param $symbol
 * @return string
 * @author: shiquan
 * @Time: 2022/9/28 23:15
 */
function strReplaces($str, $start, $len, $symbol = '*')
{
    $end = $start + $len;
    // 截取头保留的字符
    $str1 = mb_substr($str, 0, $start);
    // 截取尾保留的字符
    $str2 = mb_substr($str, $end);

    //  生产要替换的字符
    $symbol_num = '';
    for ($i = 0; $i < $len; $i++) {
        $symbol_num .= $symbol;
    }
    return $str1 . $symbol_num . $str2;
}

